package cn.hfatec.shms.system.document.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.app.AppContext;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.system.document.model.DocumentParams;
import cn.hfatec.shms.system.document.service.DocumentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/document")
public class DocumentAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "DocumentService")
    private DocumentService documentService;

    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");
            rtn = "filename=\"" + new_filename + "\"";
            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();
                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(DocumentParams documentParams, Page page, Model model) {

        Table table = documentService.queryDocumentTable(documentParams, page);
        //获取配置的上传文件路径
        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);
        String realPath = shmsProperties.getUploadPath();
        String documentPath = shmsProperties.getUploadDocumentPath();
        String uploadFilePath = realPath + documentPath;
        model.addAttribute("documentsTable", table);
        model.addAttribute("documentParams", documentParams);
        model.addAttribute("uploadFilePath", uploadFilePath);
        return "/system/document/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(DocumentParams documentParams, Page page, Model model) {
        try {
            list(documentParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/document/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 文档上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/importIndex")
    @ResponseBody
    public String saveDocument(MultipartFile file, HttpServletRequest request) {

        try {
            if (file == null) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "上传文件不能为空！", "").toString();
            }
            return documentService.saveDocument(file, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Document保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
    }

    /**
     * 文档下载
     *
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    @RequestMapping("/downloadDoc")
    @ResponseBody
    public String downloadTemplate(HttpServletRequest request, HttpServletResponse response, String fileName, String clientFileName) {
        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);
        String realPath = shmsProperties.getUploadPath();
        String documentPath = shmsProperties.getUploadDocumentPath();
        String uploadFilePath = realPath + documentPath;
        FileInputStream fileInputStream = null;
        String msg = "";
        try {

            File file = new File(uploadFilePath + "/" + fileName);

            long fileLength = file.length();

            // 设置下载参数
            clientFileName = encodeFilename(request, clientFileName);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName);
            response.addHeader("Content-Length", "" + fileLength);
            response.setContentType("application/octet-stream;charset=UTF-8");
            fileInputStream = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            // 读文件
            int iBufferSize = 65000;
            byte[] buffer = new byte[65000];
            long lReadLen = 0;
            while (lReadLen < fileLength) {
                int lRead = fileInputStream.read(buffer, 0, iBufferSize);
                lReadLen += lRead;
                out.write(buffer, 0, lRead);
            }
            out.flush();
        } catch (Exception e) {
            logger.error("下载文件失败!", e);
            msg = "下载文件失败!<a href='#' onclick='javascript:history.go(-1);'>返回</a><br/>";
            msg += e.getMessage();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
        }
        return msg;
    }
}
